if exists (select * from dbo.sysobjects where id =object_id(N'[dbo].[ZDC_PROC_DX_Po_BECheck]') and OBJECTPROPERTY(id, N'IsProcedure')= 1)
-- 删除存储过程
drop procedure [dbo].[ZDC_PROC_DX_Po_BECheck]
GO


---存储过程
create  PROC  [dbo].[ZDC_PROC_DX_Po_BECheck]  
	@sapdocno NVARCHAR(500),
    @orgid NVARCHAR(500)
AS  BEGIN 
	
    DECLARE @oldid NVARCHAR(500)
    DECLARE @poid NVARCHAR(500)
    DECLARE @oldnexid NVARCHAR(500)
    DECLARE @cnt int
    set @oldid='0'
    set @poid='0'
    set @oldnexid='0'
    select @cnt=count(*) from ZDC_SAP_PO where DOCNO_SAP=@sapdocno 
	if(@cnt >0)
    BEGIN
        select
            case when isnull(c.status,0)>1 then 0 else isnull(b.id,0) end oldid,
            case when isnull(c.status,0)>1 then 0 else isnull(c.id,0) end poid,
            isnull(a.id,0) as oldnexid
            into #sap
        from (select * From ZDC_SAP_PO where isnull(DOCNO_U9,'') ='') a 
        full join (select * From ZDC_SAP_PO where isnull(DOCNO_U9,'') !='') b on a.DOCNO_SAP=b.DOCNO_SAP
        left join PM_PurchaseOrder c on b.DOCNO_U9=c.docno and c.org=@orgid

        select 
            @oldid=oldid,
            @poid=poid,
            @oldnexid=oldnexid
        from #sap

    end
	
    select @oldid,@poid,@oldnexid

	

END